class SearchesController < ApplicationController
  def index
    @title = "Trends"
    @searches = Search.find_all_by_is_saved(true)
    @timespans = Timespan.paginate_default_to_last(params[:page])
    @new_search = Search.new(:is_saved => true)
  end
  def create
    update
  end
  def update
    ref = params[:ref]
    if params[:search][:query].strip.blank?
      session[:search] = nil if ref == 'reports'
    else
      begin
        sch = Search.find_or_create_canonicalized(params[:search])
        # try getting the search conditions to make sure no errors
        sch.conditions
        if ref == 'reports'
          session[:search] = sch
        else
          sch.mark_saved
          sch.run_on_chunks
        end
      rescue
        flash[:error] = $!.to_s
      end
    end
    redirect_to("/#{ref}")
  end
  def show
    session[:search] = Search.find(params[:id])
    redirect_to(reports_path)
  end
  def clear
    session[:search] = nil
    redirect_to(reports_path)
  end
  def save
    s = Search.find(params[:id])
    s.mark_saved
    s.run_on_chunks
    session[:search] = s
    redirect_to(reports_path)
  end
  def unsave
    Search.find(params[:id]).unsave
    session[:search] = nil
    redirect_to(request.referrer)
  end
  def drilldown
    # find the timespan and the search
    search = Search.find(params[:id])
    ts = Timespan.find(params[:timespan_id])
    
    # set up a new search
    session[:search] = Search.find_or_create_canonicalized("#{ts.search_string} (#{search.query})")
    
    # redirect to report page
    redirect_to(reports_path)
  end
  def run
    # loop over all saved searches and run them on chunks
    hits = Search.run_saved
    render(:text => "Search runs complete. #{hits} total hits.")
  end
end